package com.zj.esproxy.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.zj.esproxy.annotation.EsScan;
import com.zj.esproxy.enums.AggTypeEnum;
import com.zj.esproxy.model.Agg;
import com.zj.esproxy.model.EsInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author arthur_zhou
 * @date 2024/4/11 11:11
 */
@Slf4j
public class EsUtil {


    /**
     * 读取注解信息获取索引
     *
     * @param clazz 代理类class
     * @return es信息
     */
    public static EsInfo getEsInfo(Class<?> clazz) {
        EsInfo esInfo = new EsInfo();
        EsScan scan = AnnotatedElementUtils.getMergedAnnotation(clazz, EsScan.class);
        if (Objects.isNull(scan)) {
            log.warn("{}的@EsScan注解找不到", clazz.getName());
            return esInfo;
        }
        esInfo.setProject(scan.project());
        return esInfo;
    }

    /**
     * 解析折叠响应
     *
     * @param jsonObjectStr json字符串
     * @return 解析后的响应
     */
    public static List<Agg> getAggList(String jsonObjectStr) {
        if (StringUtils.isEmpty(jsonObjectStr)
                || !JSONValidator.Type.Object.equals(JSONValidator.from(jsonObjectStr).getType())) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(jsonObjectStr);
        List<Agg> resultList = new ArrayList<>();
        jsonObject.forEach((k, v) -> {
            if (!(v instanceof JSONObject)) {
                return;
            }
            String[] keys = k.split("_", 2);
            if (keys.length == 0 || StringUtils.isEmpty(keys[0])) {
                return;
            }
            String type = keys[0];
            // 用前缀判断聚合类型 range和normal没有前缀 是null
            AggTypeEnum aggTypeEnum = AggTypeEnum.getEnum(type);
            JSONObject v1 = (JSONObject) v;
            // 除range和normal外的只有一层
            if (Objects.nonNull(aggTypeEnum)) {
                String field;
                if (keys.length > 1) {
                    field = keys[1];
                } else {
                    return;
                }
                Agg agg = new Agg();
                agg.setType(aggTypeEnum);
                agg.setField(field);
                agg.setName(k);
                agg.setValue(v1.getBigDecimal("value"));
                resultList.add(agg);
                return;
            }
            JSONArray buckets = v1.getJSONArray("buckets");
            if (CollectionUtil.isEmpty(buckets)) {
                return;
            }
            Integer otherCounts = v1.getInteger("other_counts");
            for (int i = 0; i < buckets.size(); i++) {
                JSONObject bucketJson = buckets.getJSONObject(i);
                String key = bucketJson.getString("key");
                Agg agg = new Agg();
                // 有other_counts就是normal
                if (Objects.nonNull(otherCounts)) {
                    agg.setOtherCounts(otherCounts);
                    agg.setType(AggTypeEnum.normal);
                } else {
                    agg.setType(AggTypeEnum.range);
                }
                agg.setField(k);
                agg.setKey(key);
                agg.setName(k);
                agg.setValue(bucketJson.getBigDecimal("count"));
                bucketJson.remove("key");
                bucketJson.remove("count");
                // 子聚合
                agg.setBuckets(getAggList(bucketJson.toJSONString()));
                resultList.add(agg);
            }
        });
        if (CollectionUtil.isEmpty(resultList)) {
            return null;
        }
        return resultList;
    }
}
